package main

import (
	"database/sql"
	"fmt"
	pb "ihos/ihos"
	"log"

	tm "github.com/golang/protobuf/ptypes/timestamp"
)

type jiuzhenka struct {
	id        int32 //PK
	kh        string
	yy_bm     string
	blrq      int64
	patientid string
	hzid      int32
}

func (d *jiuzhenka) GetFromDB(id int32) error {
	sql := "SELECT id,kh,yy_bm,blrq,patientid,hzid FROM jiuzhenka WHERE id=$1"
	return DBConn.db.QueryRow(sql, id).Scan(&d.id, &d.kh, &d.yy_bm, &d.blrq, &d.patientid, &d.hzid)
}

func (d *jiuzhenka) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE jiuzhenka set kh=$1,yy_bm=$2,blrq=$3,patientid=$4,hzid=$5 where id=$6 RETURNING id"
		err = DBConn.db.QueryRow(sql, d.kh, d.yy_bm, d.blrq, d.patientid, d.hzid, d.id).Scan(&d.id)
	} else { //insert
		sql = "INSERT INTO jiuzhenka(kh,yy_bm,blrq,patientid,hzid)VALUES($1,$2,$3,$4,$5) RETURNING id"
		err = DBConn.db.QueryRow(sql, d.kh, d.yy_bm, d.blrq, d.patientid, d.hzid).Scan(&d.id)
	}
	return err
}

func (w *jiuzhenka) toPB() *pb.JiuZhenKaInfoL1 {
	return &pb.JiuZhenKaInfoL1{
		ID:        w.id,
		KH:        w.kh,
		YY:        w.yy_bm,
		BLRQ:      &tm.Timestamp{Seconds: w.blrq},
		PATIENTID: w.patientid,
		OID:       w.hzid,
	}
}

func (w *jiuzhenka) fromPB(in *pb.JiuZhenKaInfoL1) *jiuzhenka {
	w.id = in.GetID()
	w.kh = in.GetKH()
	w.yy_bm = in.GetYY()
	w.blrq = in.GetBLRQ().GetSeconds()
	w.patientid = in.GetPATIENTID()
	w.hzid = in.GetOID()
	return w
}

func (w *jiuzhenka) GetByHz(hz_id int32) (jrks []*jiuzhenka, err error) {
	//sql := "SELECT id,xm,xb,sfz,sjhm,hzid,removed FROM jiuzhenren WHERE hzid=$1"
	//return DBConn.db.QueryRow(sql, hz_id).Scan(&w.id, &w.xm, &w.xb, &w.sfz, &w.sjhm, &w.hzid, &w.removed)
	log.Println("GetByHz", hz_id)
	var rows *sql.Rows
	out := make([]*jiuzhenka, 0)
	sqlStr := ""
	if w.id > 0 {
		sqlStr = "SELECT id,kh,yy_bm,blrq,patientid,hzid FROM jiuzhenka WHERE id=" + fmt.Sprint(w.id)
	} else {
		sqlStr = "SELECT id,kh,yy_bm,blrq,patientid,hzid FROM jiuzhenka"
		cond := make([]string, 0)
		if hz_id > 0 {
			cond = append(cond, "hzid="+fmt.Sprint(hz_id))
		}
		if len(cond) > 0 {
			sqlStr += " WHERE "
			sep := ""
			for _, v := range cond {
				sqlStr += sep + v
				sep = " AND "
			}
		}
		sqlStr += " ORDER BY id DESC LIMIT 100"
	}
	// log.Println("SQL:", sqlStr)
	rows, err = DBConn.db.Query(sqlStr)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		w := &jiuzhenka{}
		if err = rows.Scan(&w.id, &w.kh, &w.yy_bm, &w.blrq, &w.patientid, &w.hzid); err != nil {
			log.Println(err)
		} else {
			log.Println(w)
			out = append(out, w)
		}
	}
	log.Println("out:", out)
	return out, nil
}
